package com.witframework.plugin.jbossrules.support;

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.Reader;
import java.util.Enumeration;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.drools.RuleBase;
import org.drools.compiler.PackageBuilder;
import org.drools.compiler.PackageBuilderConfiguration;
import org.springframework.core.io.Resource;

import com.witframework.plugin.jbossrules.RulesEngineException;


public class DSLRuleBaseLoader extends AbstractFileRuleBaseLoader {
	private static Logger logger = Logger.getLogger(DSLRuleBaseLoader.class);
	Properties mappings = null;

	public void setRuleFiles(Properties mappings) {
		this.mappings = mappings;
	}

	public RuleBase buildRuleBase() throws RulesEngineException {
		try {
			Enumeration keys=mappings.keys();
			while (keys.hasMoreElements()) {
				String key=(String)keys.nextElement();
				PackageBuilderConfiguration conf = new PackageBuilderConfiguration();
				//conf.setCompiler( PackageBuilderConfiguration.ECLIPSE);

				PackageBuilder builder = new PackageBuilder(conf);
				InputStream is;
				if(key.startsWith("/")){
					is=getClass().getResourceAsStream(key);
				}
				else{
					is=new FileInputStream(key);
				}
				Reader dsl =ChineseSource.convert(is,isChineseValid,fileCharset);

				Resource[] resources = this.getRuleFiles(new String[]{mappings.getProperty(key)});
				for(int i=0;i<resources.length;i++){
					Resource resource=resources[i];
					is=resource.getInputStream();
					Reader drl =ChineseSource.convert(is,isChineseValid,fileCharset);
					builder.addPackageFromDrl(drl, dsl);
					drl.close();
				}
				dsl.close();
				ruleBase.addPackage(builder.getPackage());
			}

			return ruleBase;
		} catch (Exception e) {
			logger.error("Exception occurred while load rules.",e);
			throw new RulesEngineException("Could not load rules", e);
		}
	}
}
